FIND_PACKAGE(PythonInterp REQUIRED)

SET(SETUP_PY_IN "${CMAKE_CURRENT_SOURCE_DIR}/setup.py.in")
SET(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py")
SET(DEPS
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/__init__.py
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/image.py
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/region.py
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/internal.py
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/wrapper.py
  ${CMAKE_CURRENT_SOURCE_DIR}/trax/server.py)
SET(OUTPUT "${CMAKE_BINARY_DIR}/distutils_timestamp")
SET(BUILD_PYTHON_DIR "${CMAKE_BINARY_DIR}/python")

CONFIGURE_FILE(${SETUP_PY_IN} ${SETUP_PY})

ADD_CUSTOM_COMMAND(OUTPUT ${OUTPUT}
                   COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build ${DISTUTILS_BUILD_FLAGS}
                   COMMAND ${CMAKE_COMMAND} -E touch ${OUTPUT}
                   WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/
                   DEPENDS ${DEPS} ${SETUP_PY} COMMENT "Running Distutils")

ADD_CUSTOM_TARGET(traxpython ALL DEPENDS ${OUTPUT})

IF (DEFINED DESTDIR)
    SET(PYTHON_ROOT "${DESTDIR}")
ELSE()
    SET(PYTHON_ROOT "${CMAKE_INSTALL_PREFIX}")
ENDIF()

IF (WIN32 OR WIN64)
# commenting out untill we figure out how to correctly install on Windows
#SET(DISTUTILS_INSTALL_FLAGS --root="%DESTDIR%" ${DISTUTILS_INSTALL_FLAGS})
ELSE()
SET(DISTUTILS_INSTALL_FLAGS "--root=${PYTHON_ROOT}" ${DISTUTILS_INSTALL_FLAGS})
ENDIF()
INSTALL(CODE "EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} install ${DISTUTILS_INSTALL_FLAGS} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/python/)" )